﻿using log4net;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Options;
using Myvas.AspNetCore.TencentCos;
using Quartz;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BackToCOS.Jobs
{
    //DisallowConcurrentExecution属性标记任务不可并行
    [DisallowConcurrentExecution]
    public class BackupJob : IJob
    {
        private readonly ILog _log = LogManager.GetLogger("NETCoreRepository", typeof(BackupJob));
        public Task Execute(IJobExecutionContext context)
        {
            try
            {
                _log.Info("当前系统时间:" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                DateTime date = DateTime.Now;
                ITencentCosHandler tencentCosHandler = IoC.AutofacContainer.Resolve<ITencentCosHandler>();
                IConfiguration configurationRoot = IoC.AutofacContainer.Resolve<IConfiguration>();
                var backDirs = configurationRoot["BackupDirs:Path"];
                if (string.IsNullOrEmpty(backDirs))
                {
                    throw new Exception("备份目录不能设置为空！");
                }
                var cosRegion = configurationRoot["TencentCos:CosRegion"];
                var bucketName = configurationRoot["TencentCos:BucketName"];
                var appId = configurationRoot["TencentCos:AppId"];
                var secretId = configurationRoot["TencentCos:SecretId"];
                var secretKey = configurationRoot["TencentCos:SecretKey"];
                var localDir = configurationRoot["BackupDirs:LocalZipDir"];
                if (string.IsNullOrEmpty(cosRegion) || string.IsNullOrEmpty(bucketName))
                {
                    throw new Exception("bucket所在区域或者bucket名称不能为空！");
                }
                string[] backupDirArray = backDirs.Split('|');
                var bucketsResult = tencentCosHandler.AllBucketsAsync().GetAwaiter().GetResult();
                List<CosBucket> result = bucketsResult.Buckets.Select(x => new CosBucket(x.Name, x.Location)).ToList();
                foreach (var item in result)
                {
                    _log.Info("拥有的bucket区域Code" + item.CosRegion.Code + "BucketName：" + item.BucketName.Name + "BucketName地址" + item.ToHttps(""));
                }
                CosBucket cosBucket = result.FirstOrDefault(x => x.CosRegion.Code == cosRegion && x.BucketName.Name == bucketName);
                if (cosBucket == null)
                {
                    throw new Exception(string.Format("找不到区域{0}区域的名称{1}的bucket！", cosRegion, bucketName));
                }
                foreach (var dir in backupDirArray)
                {
                    //判断是否已经存在
                    var backfileName = date.ToString("yyyyMMdd") + "/" + Path.GetFileName(dir) + ".zip";
                    var list = tencentCosHandler.AllObjectsAsync(cosBucket.ToHttp("").ToString(), "", int.MaxValue.ToString()).Result;
                    if (list.Contents.Count > 0 && list.Contents.Count(x => x.Key.Contains(backfileName)) > 0)
                    {

                        continue;
                    }
                    //判断7天是否已经存在
                    var day7backfileName = date.AddDays(-7).ToString("yyyyMMdd") + "/" + Path.GetFileName(dir) + ".zip";
                    if (list.Contents.Count > 0 && list.Contents.Count(x => x.Key.Contains(day7backfileName)) > 0)
                    {
                        foreach (var item in list.Contents.Where(x => x.Key.Contains(day7backfileName)))
                        {
                            var deleteRes = tencentCosHandler.DeleteObjectAsync(cosBucket.ToHttp(item.Key).ToString()).Result;
                        }
                    }
                    ZipHelper.CreateZip(dir, localDir + backfileName);
                    //目标路径
                    string desDir = backfileName;
                    string fileName = Path.GetFileName(localDir + backfileName);
                    string bucketUrl = cosBucket.ToHttps("").ToString();
                    bool success = false;
                    using (FileStream fileStream = File.OpenRead(localDir + backfileName))
                    {
                        var putresult = tencentCosHandler.PutObjectAsync(bucketUrl, desDir, fileName, fileStream);
                        _log.Info("备份的文件" + fileName + "结果：" + putresult.Result);
                        if (string.IsNullOrEmpty(putresult.Result.Host))
                            success = true;
                    }
                    //执行删除本地文件
                    if (File.Exists(localDir + backfileName) && success)
                        File.Delete(localDir + backfileName);
                }
                _log.Info("备份的文件完成,时间" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                return Task.CompletedTask;
            }
            catch (RequestFailureException ex)
            {
                JobExecutionException e2 = new JobExecutionException(ex);
                _log.Error("备份任务异常" + ex.HelpLink.ToString(), e2);
            }
            catch (Exception ex)
            {
                JobExecutionException e2 = new JobExecutionException(ex);
                _log.Error("备份任务异常", e2);
            }
            return Task.CompletedTask;
        }
    }
}
